import { defineStore } from 'pinia'
import { computed, nextTick, ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import type { MenuOption } from 'naive-ui'
import { IconPark } from '@icon-park/vue-next/es/all'
import { RouterLink } from 'vue-router'
import type { TagView } from '@/types/menu'

export const useMenuStore = defineStore('menu', () => {
	//控制页面刷新
	const isRouterActive = ref<boolean>(true)
	const menus = ref<MenuOption[]>([])
	const collapsed = ref<boolean>(false)
	const staticMenus = ref<MenuOption[]>([])
	const tagViews = ref<TagView[]>(JSON.parse(sessionStorage.getItem('tag-view') || '[]') as TagView[])
	const allMenu = computed<MenuOption[]>(() => {
		return staticMenus.value.concat(menus.value)
	})
	const setCollapsed = (value: boolean) => {
		collapsed.value = value
	}
	const reload = () => {
		isRouterActive.value = false
		nextTick(() => {
			isRouterActive.value = true
		})
	}
	/**
	 * 缓存TagViews
	 */
	const cacheTagViews = () => {
		sessionStorage.setItem('tag-view', JSON.stringify(tagViews.value))
	}
	/**
	 * 添加面包屑
	 * @param route 路由
	 * @param init 是否是初始化的时候添加，初始化添加，只添加固定的tagView
	 */
	const addTagView = (route: RouteRecordRaw, init?: boolean) => {
		if (init && (!route.meta || !route.meta.affix)) {
			return
		}
		//查找是否有添加过的tag
		const tags = tagViews.value.filter((item) => item.path === route.path)
		if (tags.length < 1) {
			tagViews.value.push({
				title: (route.meta && route.meta.title) || '',
				path: route.path || '/',
				affix: route.meta && route.meta.affix,
				icon: route.meta && route.meta.icon
			})
			cacheTagViews()
		}
	}
	/**
	 * 关闭标签页
	 * @param tag 标签参数
	 */
	const removeTagView = (tag: TagView) => {
		const index = tagViews.value.findIndex((item) => item.path === tag.path)
		if (index !== -1 && tag.affix !== true) {
			tagViews.value.splice(index, 1)
			cacheTagViews()
		}
	}
	/**
	 * 关闭右侧标签页
	 * @param tag 标签参数
	 */
	const removeTagViewOnRight = (tag: TagView) => {
		const index = tagViews.value.findIndex((item) => item.path === tag.path)
		if (index !== -1) {
			tagViews.value = tagViews.value.filter((item, i) => i <= index || item.affix === true)
			cacheTagViews()
		}
	}
	/**
	 * 删除所有标签页
	 */
	const removeAll = () => {
		tagViews.value = tagViews.value.filter((item) => item.affix === true) || []
		cacheTagViews()
	}

	/**
	 * 添加菜单
	 * @param routes 路由
	 */
	const addMenu = (routes: RouteRecordRaw[]) => {
		staticMenus.value = staticMenus.value.concat(formatRoutes(routes))
	}
	/**
	 * 渲染图标
	 * @param route 路由
	 */
	const renderIcon = (route: RouteRecordRaw) => {
		return () => (route.meta && route.meta.icon ? <IconPark type={route.meta.icon} /> : '')
	}
	/**
	 * 渲染菜单
	 * @param route 路由
	 */
	const renderLabel = (route: RouteRecordRaw) => {
		return () => <RouterLink to={route.path}>{route.meta?.title}</RouterLink>
	}
	/**
	 * 通过路由格式化菜单
	 * @param routes
	 */
	const formatRoutes = (routes: RouteRecordRaw[]): MenuOption[] => {
		const options: MenuOption[] = []
		routes.forEach((route) => {
			//隐藏菜单
			if (route.meta && route.meta.hide === true) {
				return
			}
			const menuOption: MenuOption = {
				label: renderLabel(route),
				icon: renderIcon(route),
				key: route.path || (route.meta && route.meta.active)
			}
			if (route.children) {
				const { children } = route
				const showMenu: RouteRecordRaw[] = route.children.filter((item: RouteRecordRaw) => !item.meta || item.meta.hide !== true)
				if (showMenu.length > 1) {
					menuOption.children = []
					menuOption.children = menuOption.children.concat(formatRoutes(children || []))
					//如果只有一个子菜单替换父菜单key，当前菜单高亮
				} else if (showMenu.length === 1) {
					Object.assign(menuOption, {
						label: renderLabel(showMenu[0]),
						icon: renderIcon(showMenu[0]),
						key: showMenu[0].path || (showMenu[0].meta && showMenu[0].meta.active)
					})
					//只添加能被跳转的路由
					addTagView(showMenu[0], true)
				}
			} else {
				//只添加能被跳转的路由
				addTagView(route, true)
			}
			options.push(menuOption)
		})
		return options
	}
	return { allMenu, addMenu, collapsed, setCollapsed, tagViews, addTagView, reload, isRouterActive }
})
